package com.mogist.hqc.module.main.ui

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.event.SearchEvent
import com.mogist.hqc.entitys.response.HistoryVo
import com.mogist.hqc.entitys.response.MainItemVo
import com.mogist.hqc.entitys.response.MainTypeItemVo
import com.mogist.hqc.module.main.adapter.SearchAdapter
import com.mogist.hqc.module.main.contract.SearchContract
import com.mogist.hqc.module.main.presenter.SearchPresenter
import com.mogist.hqc.module.place.ui.ScenicActivity
import com.mogist.hqc.module.route.ui.RouteMainActivity
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import kotlinx.android.synthetic.main.activity_search.*
import org.greenrobot.eventbus.EventBus
import talex.zsw.basecore.util.RegTool
import talex.zsw.basecore.util.SpTool
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.flowlayout.FlowLayout
import talex.zsw.basecore.view.other.flowlayout.TagAdapter
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.SampleHeader

/**
 * 作用：搜索
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class SearchActivity : BaseMVPActivity<SearchContract.Presenter>(), SearchContract.View
{
    private var type = ""
    private var fromMain = true
    private var history: HistoryVo? = null
    private var historyKey = Constant.OBJ_HISTORY
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("type")
                ?.let {
                    type = it
                }
        intent.getStringExtra("keyword")
                ?.let {
                    keyword = it
                }
        intent.getBooleanExtra("fromMain", true)
    }

    override fun initView()
    {
        setContentView(R.layout.activity_search)
        mPresenter = SearchPresenter(this)
    }

    override fun initData()
    {
        initRecyclerView()
        initHistory()
        if (!fromMain)
        {
            mEditText.hint = "搜索线路..."
        }
        mEditText.setText(keyword)
        mEditText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH)
            {
                keyword =
                        mEditText.text.toString()
                                .trim()
                if (RegTool.isEmpty(keyword))
                {
                    keyword = ""
                    mRvSearch.visibility = View.GONE
                }
                else
                {
                    search()
                }
            }
            false
        }
        mEditText.setClearTextListener {
            keyword = ""
            mRvSearch.visibility = View.GONE
        }
    }

    @Optional
    @OnClick(R.id.mTvCancel, R.id.mTvDelete)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvCancel ->
                {
                    finish()
                }
                R.id.mTvDelete ->
                {
                    showDialog(SweetAlertDialog.NORMAL_TYPE,
                               "是否清空搜索历史？",
                               "",
                               "确定",
                               "取消",
                               { clearSearch() },
                               null)
                }
            }
        }
    }

    var keyword = ""
    private fun search()
    {
        addSearch(keyword)
        if (!fromMain)
        {
            val body = BaseModel()
            body.startLat = SpTool.getString(Constant.STR_LATITUDE)
            body.startLong = SpTool.getString(Constant.STR_LONGITUDE)
            body.type = type
            body.keyWord = keyword
            body.distance = Constant.STR_DISTANCE
            mPresenter.getData(HttpDto(Constant.TYPE_LIST, body).setType(HttpDto.GET))
        }
        else
        {
            EventBus.getDefault()
                    .post(SearchEvent(keyword))
            finish()
        }
    }

    override fun bindTypes(data: MainTypeItemVo)
    {
        if (!fromMain)
        {
            if (data.list == null || data.list.isEmpty())
            {
                adapter.isUseEmpty(true)
                adapter.replaceData(data.list)
                mRvSearch.visibility = View.VISIBLE
            }
            else
            {
                EventBus.getDefault()
                        .post(data)
                finish()
            }
        }
        else
        {
            adapter.isUseEmpty(true)
            adapter.replaceData(data.list)
            mRvSearch.visibility = View.VISIBLE
        }
    }

    private val adapter = SearchAdapter()
    private fun initRecyclerView()
    {
        adapter.setOnItemClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                val vo = adapter.getItem(position) as MainItemVo
                if (vo.type == "ROUTE")
                {
                    val intent = Intent(this@SearchActivity, RouteMainActivity::class.java)
                    intent.putExtra("id", vo.id)
                    startActivity(intent)
                }
                else
                {
                    val intent = Intent(this@SearchActivity, ScenicActivity::class.java)
                    intent.putExtra("id", vo.id)
                    startActivity(intent)
                }
            }
        }
        adapter.emptyView = SampleHeader(this@SearchActivity, mRvSearch.width, mRvSearch.height)
        adapter.isUseEmpty(false)
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRvSearch.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                          R.color.transparent))
        mRvSearch.layoutManager = LinearLayoutManager(this@SearchActivity)
        mRvSearch.adapter = adapter
    }

    // ========================= 历史记录 ================================
    private fun initHistory()
    {
        history = SpTool.getObject(historyKey, HistoryVo::class.java)
        if (history == null)
        {
            history = HistoryVo()
        }

        if (history!!.search.isEmpty())
        {
            mLLHistory.visibility = View.GONE
            return
        }
        else
        {
            mLLHistory.visibility = View.VISIBLE
        }
        val mAdapter = object : TagAdapter<String>(history!!.search)
        {
            override fun getView(parent: FlowLayout, position: Int, s: String): View
            {
                val tv = layoutInflater.inflate(R.layout.view_tag, mFlowLayout, false) as TextView
                if (s.length < 10)
                {
                    tv.text = s
                }
                else
                {
                    tv.text = s.substring(0, 9) + "…"
                }

                tv.setOnClickListener {
                    mEditText.setText(s)
                    keyword = s
                    search()
                }
                return tv
            }
        }
        mFlowLayout.setAdapter(mAdapter)
        mFlowLayout.setMaxSelectCount(1) //设置最大选中数目
        mAdapter.setSelectedList(0) //设置默认选中
    }

    private fun addSearch(newSearch: String)
    {
        if (history == null)
        {
            history = HistoryVo()
        }
        mLLHistory.visibility = View.VISIBLE

        history!!.search.add(0, newSearch)

        if (history!!.search.size > 1)
        {
            for (i in 1 until history!!.search.size)
            {
                if (history!!.search[i] == newSearch)
                {
                    history!!.search.removeAt(i)
                    break
                }
            }
            if (history!!.search.size > 10)
            {
                history!!.search.removeAt(10)
            }
        }
        SpTool.saveObject(historyKey, history)
        // 刷新界面的相关操作
        initHistory()
    }

    private fun clearSearch()
    {
        if (history != null)
        {
            history = HistoryVo()
        }
        SpTool.saveObject(historyKey, history)
        // 刷新界面的相关操作
        initHistory()
        disDialog()
    }
}